import Axios from "axios"
import store from "../store/store";
import router from "../router";

// 创建基础的网络请求工具，并完成相应的配置
const Http = Axios.create({
  // 基础路径
  baseURL: "http://123.56.1.117:9000/",
  timeout: 10000,

  // get、post请求修改
  headers: {
    get: {
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
    },
    post: {
      'Content-Type': 'application/json;charset=utf-8'
    }
  }
})

// 请求拦截器
Http.interceptors.request.use((config) => {
  if(store.state.token.flag == true){
    config.headers.common['token'] = store.state.token.token;
    config.headers.common['account'] = store.state.token.account;
  }
  return config;
}, (error) => {
  console.error("服务器异常，请联系管理员！"+error);
})

// 响应拦截器拦
Http.interceptors.response.use(

  // 请求成功
  response=>{


    if (response.status === 200) {
      return Promise.resolve(response.data);
    // 权限不足
    } else if(response.status === 403){
      // 判断是否已登录，已登录则token错误需要重新登录
      if(store.state.token.flag == true){
        store.commit("updateToken",{flag: false, time: -1, token: "", account: ""});
        window.localStorage.removeItem("token");
      }

      store.commit("updateError", "用户未登录或登录失效")
      router.push("/login");

    } else {
      return Promise.reject(response);
    }
  },

  // 请求失败
  error =>{
    if(error.response.status === 403){
      // 判断是否已登录，已登录则token错误需要重新登录
      if(store.state.token.flag == true){
        store.commit("updateToken",{flag: false, time: -1, token: "", account: ""});
        window.localStorage.removeItem("token");
      }
      store.commit("updateError", "用户未登录或登录失效")
      router.push("/login");
    } else {
      return Promise.reject(error.response);
    }
  }

)

// 导出
export default Http;
